/**
 * @file 工单操作-收单
 * @author yangjiangming <449654337@qq.com>
 * @date 2018-12-10 20:13:16
 */
layui.define(['layer', 'form', 'list_modify_common', 'laytpl', 'table', 'NP', '$http'], function (exports) {
    let $ = layui.$;
    let table = layui.table;
    let form = layui.form;
    let laytpl = layui.laytpl;
    let opCommonUtils = layui.list_modify_common;
    let NP = layui.NP;
    let $http = layui.$http;
    let newServiceItemList = [];

    var GET_TIERED_TOTAL_PRICE='/work/modify/serviceitem/tieredtotalprice.action';

    /**
     * 错误提示
     * @param ele
     * @param str
     * @returns {boolean}
     */
    let tips = function (ele, str,callback) {
        toast({
            title: str,
            icon: 2,
            time: 2000
        });
        $(ele).focus();
        $(ele).val('');
        if(typeof callback === 'function'){
            callback();
        }
        return false;
    };
    /**
     * 提示消息
     * @param str {string} 提示信息
     * @returns {*}
     */
    function toast(opt) {
        layer.msg(opt.title, {
            icon: opt.icon,
            time: opt.time || 1000,
        }, function () {
            if (opt.icon == 1) {
                   opCommonUtils.goOperateHome();
            //    location.reload();
            }
        })
    };

    /**
     * 取两位小数
     * @param a
     * @param num
     * @returns {*}
     */
    function subStringNum(a, num) {
        var a_type = typeof (a);
        if (a_type == "number") {
            var aStr = a.toString();
            var aArr = aStr.split('.');
        } else if (a_type == "string") {
            var aArr = a.split('.');
        }

        if (aArr.length > 1) {
            a = aArr[0] + "." + aArr[1].substr(0, num);
        }
        return a
    }

    /**
     * 获取某个元素下子元素的文本值
     * @param item
     * @param ele
     * @returns {jQuery}
     */
    function getText(item, ele) {
        return $(item).find(ele).text() || $(item).find(ele).val();
    }


    /**
     * 保存
     * @param data {object} data,success,fail属性
     */
    function request(data, btn) {
        var url = '../modify/save/checkout.action';

        $http.lockSave(url, data, btn).then(function () {
            layer.msg('操作成功', {icon: 1, time: 1000}, function () {
                opCommonUtils.goOperateHome();
            });
        }, function (msg) {
            layer.msg(msg);
        });
    }

    /**
     * 保存按钮
     */
    function initSubmit() {
        form.on('submit(save-btn)', function (obj) {
            let data = obj.field;

            let prop = getSimpleCheckOutData(data);
            if (data.resultStatus != 2) {
                request(prop, obj.elem);
                return false;
            }

            let checkOutConf = masterList.checkOutConf;
            let totalAmount = masterList.totalAmount;
            if (checkOutConf && totalAmount && checkOutConf.amount && totalAmount < checkOutConf.amount) {
                layer.open({
                    title: '确认',
                    content: '此订单按收入小于成功标准，确认改为：成功吗？',
                    btn: ['确认', '取消'],
                    yes: function (index, layero) {
                        layer.close(index);
                        request(prop, obj.elem);
                    },
                    cancel: function (index, layero) {
                        layer.close(index);
                    }
                });
            } else {
                request(prop, obj.elem);
            }

            return false;
        })
    };

    function getSimpleCheckOutData(data) {
        let prop = {
            workId: data.workId,
            orderId: data.orderId,
            resultStatus: data.resultStatus,
            operatorRemark: data.operatorRemark,
            serviceItemVOList: newServiceItemList
        };
        return prop;
    }

    /**
     * 点击贴花缩略图, 查看大图
     */
    function bigImage() {
        layer.photos({
            photos: '.applique-list',
            anim: 0
        })
    }

    /**
     * 初始化页面;
     */
    function initPage() {

    }

    /**
     * 初始化页面事件
     */
    function initEvent() {

        //输入框正在输入时
        $("input[name='internalSettlementPrice'], input[name='internalTotalPrice']").on('input',function(){
            var $this = $(this);
            var value = $this.val()
                .replace(/\-{1,}/g,'')
                .replace(/[^\d.-]/g, '')
                .replace(/^\./g, '')
                .replace(/\.{2,}/g, '.')
                .replace('.', '$#$').replace(/\./g, '').replace('$#$', '.')
                .replace(/^(\d+)\.(\d\d).*$/, '$1.$2');
            // 内部价不能超过10W
            if (value > 100000){
                value = 100000;
            }
            $this.val(value);
        });

        // 内部单价-输入框失去焦点时
        $("input[name='internalSettlementPrice']").on('blur',function(){
            let $this = $(this);
            let price = opCommonUtils.accMul($this.val(), 100);
            let number = $this.parent().parent().find('.item-number').text();
            // 阶梯总价
            let tempTotalPrice;

            let servItemId = $this.attr("data-service-item-id");
            let proExtId = $this.attr("data-pro-ext-id");
            let serviceItem = masterList.orderServiceItemList.find((item) => (item.servItemId == servItemId && item.proExtId == proExtId));
            if (serviceItem.itemPrice == 0 && serviceItem.number > 1) {
                var params = {
                    orderId: $("input[name='orderId']").val(),
                    itemId: Number.parseInt(curr.servItemId),
                    number: Number.parseInt(curr.number),
                    detailList: serviceItem.itemDetailList
                };
                $.ajax({
                    url: GET_TIERED_TOTAL_PRICE,
                    type: 'post',
                    async: false,
                    contentType: "application/json",
                    dataType: "json",
                    data: JSON.stringify(params),
                    success: function (response) {
                        if (response.status === 200) {
                            tempTotalPrice = response.data;
                        } else {
                            layer.msg("请求阶梯价失败" + response.message);
                        }
                    },
                    error: function () {
                        layer.msg('网络错误，请重试');
                    }
                })
            } else {
                tempTotalPrice = opCommonUtils.accMul(price, number);
            }

            let item = newServiceItemList.find((item) => (item.servItemId == servItemId && item.proExtId == proExtId));

            if (item){
                item.internalSettlementPrice = price;
                item.internalTotalPrice = tempTotalPrice;
            } else {
                newServiceItemList.push({
                    proExtId: serviceItem.proExtId,
                    servItemId: serviceItem.servItemId,
                    servItemName: serviceItem.servItemName,
                    oldInternalSettlementPrice: serviceItem.internalSettlementPrice,
                    internalSettlementPrice: price,
                    internalTotalPrice: tempTotalPrice
                });
            }

            // 设置总价
            $this.parent().next().find('input[name="internalTotalPrice"]').val(NP.divide(tempTotalPrice, 100).toFixed(2));

            // 计算总价
            let totalPrice = 0;
            $('input[name="internalTotalPrice"]').each(function () {
                totalPrice = opCommonUtils.accAdd(totalPrice, $(this).val());
            });
            $("#internalTotalPrice").text(totalPrice);
        });

        // 内部总价-输入框失去焦点时
        $("input[name='internalTotalPrice']").on('blur',function(){
            let $this = $(this);
            let tempTotalPrice = opCommonUtils.accMul($this.val(), 100);
            let number = $this.parent().parent().find('.item-number').text();
            let price = NP.divide(tempTotalPrice, number).toFixed(0);

            let servItemId = $this.attr("data-service-item-id");
            let proExtId = $this.attr("data-pro-ext-id");
            let serviceItem = masterList.orderServiceItemList.find((item) => (item.servItemId == servItemId && item.proExtId == proExtId));
            let item = newServiceItemList.find((item) => (item.servItemId == servItemId && item.proExtId == proExtId));

            if (item){
                item.internalSettlementPrice = price;
                item.internalTotalPrice = tempTotalPrice;
            } else {
                newServiceItemList.push({
                    proExtId: serviceItem.proExtId,
                    servItemId: serviceItem.servItemId,
                    servItemName: serviceItem.servItemName,
                    oldInternalSettlementPrice: serviceItem.internalSettlementPrice,
                    internalSettlementPrice: price,
                    internalTotalPrice: tempTotalPrice
                });
            }

            $this.parent().prev().find('input[name="internalSettlementPrice"]').val(NP.divide(price, 100).toFixed(2));

            // 计算总价
            let totalPrice = 0;
            $('input[name="internalTotalPrice"]').each(function () {
                totalPrice = opCommonUtils.accAdd(totalPrice, $(this).val());
            });
            $("#internalTotalPrice").text(totalPrice);
        });

        initSubmit();

        //查看贴花大图
        bigImage();

    }

    // 程序入口
    function init() {

        // 初始化页面
        initPage();

        // 初始化事件
        initEvent();

    }


    // 初始化
    init();

    exports('oms_work_modify_checkout');
});
